<?php
require_once 'application/libraries/openid.php';
require_once 'application/helpers/HashGenerator.php';

class Validate extends AsbtractRestController {
	public function __construct() {
		parent::__construct();
	}
	
	public function google_get() {
		$openid = new LightOpenID('localhost');
		if($openid->mode) {
			if($openid->mode == 'cancel') {
				return $this->response($this->constructErrorMsg(ErrorMessgaes::$USER_AUTH_GOOGLE_CODE, ErrorMessgaes::$USER_AUTH_GOOGLE_CANCELED_MSG));
			} elseif ($openid->validate()) {
				$arr_resp = $this->storeDbData($openid);
				if (!isset($arr_resp)) {
					$this->storeSessionData($openid);
				} else {
					return $this->response($arr_resp);
				}
			}
		}
	}
	
	private function storeDbData($openid) {
		$id = $this->session->userdata('id');
		if (!$id || $id != $openid->identity) {
			$external_login = $openid->getAttributes();
			$user = $this->load->model("User");
			$error_msg = $this->User->insertUser($external_login['contact/email'],HashGenerator::hashClearPassword($openid->identity),'Google');
			if ($error_msg != ErrorMessgaes::$USER_AUTH_EXIST_MSG) {
				return $this->constructErrorMsg(ErrorMessgaes::$USER_AUTH_GOOGLE_CODE,$error_msg);
			}
		}
	}
	
	private function storeSessionData($openid) {
		$id = $this->session->userdata('id');
		if (!$id || $id != $openid->identity) {
			$external_login = $openid->getAttributes();
			$this->session->set_userdata(array('name' => $external_login['namePerson/first']." ".$external_login['namePerson/last'],
					'email' => $external_login['contact/email'], 'id' =>  $openid->identity));
		}
	}
	
}